package com.tgy.leetcode;

import java.util.Arrays;
import java.util.List;
import java.util.Stack;
import java.util.stream.Collectors;

/**
 * @Author: tgy
 * @Date: 12/30/20 9:39 AM
 */
public class _105_从前序与中序遍历序列构造二叉树 {

    public TreeNode BuildTree(int[] preorder, int[] inorder) {

        if (inorder == null || preorder == null || inorder.length != preorder.length ) {

            return null;
        }

        if (preorder.length == 0) {

            return null;
        }

        Stack<TreeNode> stack = new Stack<>();

        TreeNode root = new TreeNode(preorder[0]);

        stack.push(root);

        int inorderIndex = 0,preVal;
        for (int i = 1; i < preorder.length; i++) {

            preVal = preorder[i];
            TreeNode node = stack.peek();

            if (inorder[inorderIndex] != node.val) {

                TreeNode newNode = new TreeNode(preorder[i]);
                node.left = newNode;
                stack.push(newNode);
            }else {

                while (!stack.isEmpty() && stack.peek().val == inorder[inorderIndex]) {

                    node = stack.pop();
                    inorderIndex++;
                }


                node.right = new TreeNode(preVal);
                stack.push(node.right);
            }
        }


        return root;
    }
}
